package com.atguigu.juc.chap10;

import java.util.concurrent.*;

public class CompletableFutureDemo06_01 {

	public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1、创建线程池对象
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        // 2.1、创建任务1
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 任务 1 开始");
            try {
                TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}
            System.out.println(Thread.currentThread().getName() + " 任务 1 结束");

            return "task01 result";
        }, threadPool);

        // 2.2、创建任务2
        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 任务 2 开始");
            try {
                TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {}
            System.out.println(Thread.currentThread().getName() + " 任务 2 结束");

            return "task02 result";
        }, threadPool);

        // 3、allOf 方法用来汇总各个任务
        CompletableFuture<Void> future = CompletableFuture.allOf(future01, future02);

        // 4、所有具体任务全部结束，才会触发总任务 future 的完成事件
        future.whenComplete((Object taskResult, Throwable throwable)->{
            System.out.println(Thread.currentThread().getName() + " 汇总结果 = " + taskResult);
        });

        // 5、如果想要具体任务的结果，需要调用具体任务的 get() 方法
        String task01Result = future01.get();
        System.out.println(Thread.currentThread().getName() + " task01Result = " + task01Result);
        String task02Result = future02.get();
        System.out.println(Thread.currentThread().getName() + " task02Result = " + task02Result);


        // 6、关闭线程池
        threadPool.shutdown();
    }
}